package com.gemframework.common.exception;

import com.gemframework.common.util.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理API自定义异常
     */
    @ExceptionHandler(ApiException.class)
    public Object handleRRException(ApiException e) {
        log.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", e.getMsg());
        map.put("data", e.getData());
        map.put("code", e.getCode());
        return map;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ApiResult handleDuplicateKeyException(DuplicateKeyException e) {
        log.debug(e.getMessage(), e);
        return ApiResult.error("数据库中已存在该记录");
    }

    @ExceptionHandler(ValidationException.class)
    public ApiResult handle(ValidationException exception) {
        String msg = "参数错误";
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                if (StringUtils.isNotEmpty(item.getMessage())) {
                    msg = item.getMessage();
                    break;
                }
            }
        } else {
            msg = exception.getMessage();
        }
        return ApiResult.error(msg);
    }

}
